package juc.juccore.flowcontrol.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatch1And2 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(5);
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 1; i <= 5; i++) {
            int no = i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    System.out.println("No" + no + "准备完毕,等待发令枪 ");
                    try {
                        countDownLatch.await();
                        System.out.println(no + "号" + "开始跑步");
                        Thread.sleep((long) Math.random() * 1000);
                        System.out.println("No" + no + "到达终点");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        end.countDown();
                    }

                }
            };
            executorService.submit(runnable);
        }
        Thread.sleep(5000);
        System.out.println("发令枪响,比赛开始");
        countDownLatch.countDown();
        end.await();
        System.out.println("全部达到终点,比赛结束");
        executorService.shutdown();
    }
}

